<?php

if (!defined('IN_SEXMALL'))
{
	die('Hacking attempt');
}

/**
 * 取得当前位置和页面标题
 *
 * @access  public
 * @param   integer     $cat    分类编号（只有商品及分类、文章及分类用到）
 * @param   string      $str    商品名、文章标题或其他附加的内容（无链接）
 * @return  array
 */
function assign_ur_here($str = '', $arr=array())
{
	/* 初始化“页面标题”和“当前位置” */
	$ur_here    = '<li><a href="index.html">首页</a></li>';

	/* 处理最后一部分 */
	if (!empty($str))
	{
		//$ur_here    .= ' <code>&gt;</code> ' . $str;
		switch ($str)
		{
			case 'brand' :
				if ($arr['brand_id'])
				{
					$schedule_list = get_schedule();
					$schedule = array();
					foreach ($schedule_list AS $key => $val){
						if ($val['link_type'] == 0 && $val['id'] == $arr['brand_id']){
							$schedule = $val;
							break;
						}
					}

					$ur_here .= '<li class="gap"></li><li>'.$schedule['name'].'</li>';
				}
				else if ($arr['cat_id'])
				{
					$categorys = get_category();
					$category = array();
					foreach ($categorys AS $key => $val){
						if ($val['id'] == $arr['cat_id']){
							$category = $val;
							break;
						}
					}

					$ur_here .= '<li class="gap"></li><li>'.$category['name'].'</li>';
				}

				break;
		}

	}

	return $ur_here;
}


/**
 * 根据提供的数组编译成页面标题
 *
 * @access  public
 * @param   string  $type   类型
 * @param   array   $arr    分类数组
 * @return  string
 */
function build_pagetitle($arr, $type = 'category')
{
	$str = '';

	foreach ($arr AS $val)
	{
		$str .= htmlspecialchars($val['cat_name']) . '_';
	}

	return $str;
}

/**
 * 根据提供的数组编译成当前位置
 *
 * @access  public
 * @param   string  $type   类型
 * @param   array   $arr    分类数组
 * @return  void
 */
function build_urhere($arr, $type = 'category')
{
	krsort($arr);

	$str = '';
	foreach ($arr AS $val)
	{
		switch ($type)
		{
			case 'brand':
				$args = array('cid' => $val['cat_id']);
				break;
		}

		$str .= ' <code>&gt;</code> <a href="' . build_uri($type, $args). '">' . htmlspecialchars($val['cat_name']) . '</a>';
	}

	return $str;
}


/**
 *  生成给pager.lbi赋值的数组
 *
 * @access  public
 * @param   string      $url        分页的链接地址(必须是带有参数的地址，若不是可以伪造一个无用参数)
 * @param   array       $param      链接参数 key为参数名，value为参数值
 * @param   int         $record     记录总数量
 * @param   int         $page       当前页数
 * @param   int         $size       每页大小
 *
 * @return  array       $pager
 */
function get_pager($url, $param, $record_count, $page = 1, $size = 10 ,$rewrite=0)
{
	$size = intval($size);
	if ($size < 1)
	{
		$size = 10;
	}

	$page = intval($page);
	if ($page < 1)
	{
		$page = 1;
	}

	$record_count = intval($record_count);

	$page_count = $record_count > 0 ? intval(ceil($record_count / $size)) : 1;	// 共x页
	if ($page > $page_count)
	{
		$page = $page_count;
	}
	/* 分页样式 */
	$pager['styleid'] = isset($GLOBALS['_CFG']['page_style'])? intval($GLOBALS['_CFG']['page_style']) : 0;

	$page_prev  = ($page > 1) ? $page - 1 : 1;
	$page_next  = ($page < $page_count) ? $page + 1 : $page_count;

	/* 将参数合成url字串 */
	$param_url = '?';
	foreach ($param AS $key => $value)
	{
		$param_url .= $key . '=' . $value . '&';
	}

	$pager['url']          = $url;
	$pager['start']        = ($page -1) * $size;
	$pager['page']         = $page;
	$pager['size']         = $size;
	$pager['record_count'] = $record_count;
	$pager['page_count']   = $page_count;

	if ($pager['styleid'] == 0)
	{
		if($rewrite)
		{
			$param['curpage'] = 1;
			$pager['page_first']   	= $url . '-'.implode('-',$param).'.html';
			$param['curpage'] 		= $page_prev;
			$pager['page_prev']    	= $url . '-'.implode('-',$param).'.html';
			$param['curpage'] 		= $page_next;
			$pager['page_next']    	= $url . '-'.implode('-',$param).'.html';
			$param['curpage'] 		= $page_count;
			$pager['page_last']    	= $url . '-'.implode('-',$param).'.html';
		}
		else
		{
			$pager['page_first']   = ($page > 1) ? $url . $param_url . 'page=1' : '';
			$pager['page_prev']    = ($page > 1) ? $url . $param_url . 'page=' . $page_prev : '';
			$pager['page_next']    = ($page < $page_count && $page_count > 1) ? $url . $param_url . 'page=' . $page_next : '';
			$pager['page_last']    = ($page < $page_count && $page_count > 1) ? $url . $param_url . 'page=' . $page_count : '';
		}
		$pager['array']  = array();
		for ($i = 1; $i <= $page_count; $i++)
		{
			$pager['array'][$i] = $i;
		}
	}
	else
	{
		die('pager error');
		$_pagenum 	= 10;     // 显示的页码
		$_offset 	= 2;       // 当前页偏移值
		$_from = $_to = 0;  // 开始页, 结束页
		if($_pagenum > $page_count)	// 不够10页
		{
			$_from = 1;
			$_to = $page_count;
		}
		else
		{
			$_from = $page - $_offset;
			$_to = $_from + $_pagenum - 1;

			if($_from < 1)
			{
				$_to = $page + 1 - $_from;
				$_from = 1;
				if($_to - $_from < $_pagenum)
				{
					$_to = $_pagenum;
				}
			}
			elseif($_to > $page_count)
			{
				$_from = $page_count - $_pagenum + 1;
				$_to = $page_count;
			}
		}


		$url_format = $url . $param_url . 'page=';
		$pager['page_first'] = ($page - $_offset > 1 && $_pagenum < $page_count) ? $url_format . 1 : '';
		$pager['page_prev']  = ($page > 1) ? $url_format . $page_prev : '';
		$pager['page_next']  = ($page < $page_count) ? $url_format . $page_next : '';
		$pager['page_last']  = ($_to < $page_count) ? $url_format . $page_count : '';
		$pager['page_kbd']  = ($_pagenum < $page_count) ? true : false;
		$pager['page_number'] = array();
		for ($i=$_from;$i<=$_to;++$i)
		{
			$pager['page_number'][$i] = $url_format . $i;
		}
	}
	$pager['search'] = $param;

	return $pager;
}

/**
 * 获得浏览器名称和版本
 *
 * @access  public
 * @return  string
 */
function get_user_browser()
{
	if (empty($_SERVER['HTTP_USER_AGENT']))
	{
		return '';
	}

	$agent       = $_SERVER['HTTP_USER_AGENT'];
	$browser     = '';
	$browser_ver = '';

	if (preg_match('/MSIE\s([^\s|;]+)/i', $agent, $regs))
	{
		$browser     = 'Internet Explorer';
		$browser_ver = $regs[1];
	}
	elseif (preg_match('/FireFox\/([^\s]+)/i', $agent, $regs))
	{
		$browser     = 'FireFox';
		$browser_ver = $regs[1];
	}
	elseif (preg_match('/Maxthon/i', $agent, $regs))
	{
		$browser     = '(Internet Explorer ' .$browser_ver. ') Maxthon';
		$browser_ver = '';
	}
	elseif (preg_match('/Opera[\s|\/]([^\s]+)/i', $agent, $regs))
	{
		$browser     = 'Opera';
		$browser_ver = $regs[1];
	}
	elseif (preg_match('/OmniWeb\/(v*)([^\s|;]+)/i', $agent, $regs))
	{
		$browser     = 'OmniWeb';
		$browser_ver = $regs[2];
	}
	elseif (preg_match('/Netscape([\d]*)\/([^\s]+)/i', $agent, $regs))
	{
		$browser     = 'Netscape';
		$browser_ver = $regs[2];
	}
	elseif (preg_match('/safari\/([^\s]+)/i', $agent, $regs))
	{
		$browser     = 'Safari';
		$browser_ver = $regs[1];
	}
	elseif (preg_match('/NetCaptor\s([^\s|;]+)/i', $agent, $regs))
	{
		$browser     = '(Internet Explorer ' .$browser_ver. ') NetCaptor';
		$browser_ver = $regs[1];
	}
	elseif (preg_match('/Lynx\/([^\s]+)/i', $agent, $regs))
	{
		$browser     = 'Lynx';
		$browser_ver = $regs[1];
	}

	if (!empty($browser))
	{
		return addslashes($browser . ' ' . $browser_ver);
	}
	else
	{
		return 'Unknow browser';
	}
}

/**
 * 判断是否为搜索引擎蜘蛛
 *
 * @access  public
 * @return  string
 */
function is_spider($record = FALSE)
{
	static $spider = NULL;

	if ($spider !== NULL)
	{
		return $spider;
	}

	if (empty($_SERVER['HTTP_USER_AGENT']))
	{
		$spider = '';

		return '';
	}

	$searchengine_bot = array(
        'googlebot',
        'mediapartners-google',
        'baiduspider+',
        'msnbot',
        'yodaobot',
        'yahoo! slurp;',
        'yahoo! slurp china;',
        'iaskspider',
        'sogou web spider',
        'sogou push spider'
        );

        $searchengine_name = array(
        'GOOGLE',
        'GOOGLE ADSENSE',
        'BAIDU',
        'MSN',
        'YODAO',
        'YAHOO',
        'Yahoo China',
        'IASK',
        'SOGOU',
        'SOGOU'
        );

        $spider = strtolower($_SERVER['HTTP_USER_AGENT']);

        foreach ($searchengine_bot AS $key => $value)
        {
        	if (strpos($spider, $value) !== false)
        	{
        		$spider = $searchengine_name[$key];

        		if ($record === true)
        		{
        			//$GLOBALS['db']->autoReplace($GLOBALS['wap']->table('searchengine'), array('date' => local_date('Y-m-d'), 'searchengine' => $spider, 'count' => 1), array('count' => 1));
        		}

        		return $spider;
        	}
        }

        $spider = '';

        return '';
}

/**
 * 获得客户端的操作系统
 *
 * @access  private
 * @return  void
 */
function get_os()
{
	if (empty($_SERVER['HTTP_USER_AGENT']))
	{
		return 'Unknown';
	}

	$agent = strtolower($_SERVER['HTTP_USER_AGENT']);
	$os    = '';

	if (strpos($agent, 'win') !== false)
	{
		if (strpos($agent, 'nt 5.1') !== false)
		{
			$os = 'Windows XP';
		}
		elseif (strpos($agent, 'nt 5.2') !== false)
		{
			$os = 'Windows 2003';
		}
		elseif (strpos($agent, 'nt 5.0') !== false)
		{
			$os = 'Windows 2000';
		}
		elseif (strpos($agent, 'nt 6.0') !== false)
		{
			$os = 'Windows Vista';
		}
		elseif (strpos($agent, 'nt') !== false)
		{
			$os = 'Windows NT';
		}
		elseif (strpos($agent, 'win 9x') !== false && strpos($agent, '4.90') !== false)
		{
			$os = 'Windows ME';
		}
		elseif (strpos($agent, '98') !== false)
		{
			$os = 'Windows 98';
		}
		elseif (strpos($agent, '95') !== false)
		{
			$os = 'Windows 95';
		}
		elseif (strpos($agent, '32') !== false)
		{
			$os = 'Windows 32';
		}
		elseif (strpos($agent, 'ce') !== false)
		{
			$os = 'Windows CE';
		}
	}
	elseif (strpos($agent, 'linux') !== false)
	{
		$os = 'Linux';
	}
	elseif (strpos($agent, 'unix') !== false)
	{
		$os = 'Unix';
	}
	elseif (strpos($agent, 'sun') !== false && strpos($agent, 'os') !== false)
	{
		$os = 'SunOS';
	}
	elseif (strpos($agent, 'ibm') !== false && strpos($agent, 'os') !== false)
	{
		$os = 'IBM OS/2';
	}
	elseif (strpos($agent, 'mac') !== false && strpos($agent, 'pc') !== false)
	{
		$os = 'Macintosh';
	}
	elseif (strpos($agent, 'powerpc') !== false)
	{
		$os = 'PowerPC';
	}
	elseif (strpos($agent, 'aix') !== false)
	{
		$os = 'AIX';
	}
	elseif (strpos($agent, 'hpux') !== false)
	{
		$os = 'HPUX';
	}
	elseif (strpos($agent, 'netbsd') !== false)
	{
		$os = 'NetBSD';
	}
	elseif (strpos($agent, 'bsd') !== false)
	{
		$os = 'BSD';
	}
	elseif (strpos($agent, 'osf1') !== false)
	{
		$os = 'OSF1';
	}
	elseif (strpos($agent, 'irix') !== false)
	{
		$os = 'IRIX';
	}
	elseif (strpos($agent, 'freebsd') !== false)
	{
		$os = 'FreeBSD';
	}
	elseif (strpos($agent, 'teleport') !== false)
	{
		$os = 'teleport';
	}
	elseif (strpos($agent, 'flashget') !== false)
	{
		$os = 'flashget';
	}
	elseif (strpos($agent, 'webzip') !== false)
	{
		$os = 'webzip';
	}
	elseif (strpos($agent, 'offline') !== false)
	{
		$os = 'offline';
	}
	else
	{
		$os = 'Unknown';
	}

	return $os;
}


/**
 * 显示一个提示信息
 *
 * @access  public
 * @param   string  $content
 * @param   string  $link
 * @param   string  $href
 * @param   string  $type               信息类型：warning, error, info
 * @param   string  $auto_redirect      是否自动跳转
 * @return  void
 */
function show_message($content, $links = '', $hrefs = '', $type = 'info', $auto_redirect = false)
{
	$msg['content'] = $content;
	if (is_array($links) && is_array($hrefs))
	{
		if (!empty($links) && count($links) == count($hrefs))
		{
			foreach($links as $key =>$val)
			{
				$msg['url_info'][$val] = $hrefs[$key];
			}
			$msg['back_url'] = $hrefs['0'];
		}
	}
	else
	{
		$link   = empty($links) ? '上一页' : $links;
		$href 	= empty($hrefs) ? 'javascript:history.back()' : $hrefs;
		$msg['url_info'][$link] = $href;
		$msg['back_url'] = $href;
	}

	$msg['type']    = $type;

	$position = assign_ur_here(0, '系统消息');
	$GLOBALS['smarty']->assign('page_title', $position['title']);   // 页面标题
	$GLOBALS['smarty']->assign('ur_here',    $position['ur_here']); // 当前位置

	// OM 统计（用于跳转到下一页面时的统计）
	$om_act_url = wap_getcookie('om_act_url');
	if ($om_act_url)
	{
		wap_setcookie('om_act_url');
		$GLOBALS['smarty']->assign('om_act_url', $om_act_url);
	}

	$GLOBALS['smarty']->assign('auto_redirect', $auto_redirect);
	$GLOBALS['smarty']->assign('message', $msg);

	$GLOBALS['smarty']->display('message.dwt');
	exit;
}


/**
 * 用户登录
 * @param	string	$username 		登录用户名
 * @param	string	$password		登录密码
 * @param	bool	$remember		是否记住登录
 * @param	bool	$auto_login		是否自动登录，自动登录不重写cookie
 * */
function user_login($username='', $password='', $remember=false, $auto_login=false)
{
	global $mem, $mInterface;

	$result = $mInterface->loginUserBase($username, $password);

	// 登录成功，记录登录状态
	if (is_array($result) && $result['status'] && is_array($result['result']))
	{
		$user = $result['result'];

		if (!$auto_login)
		{
			$str = substr(md5(AUTH_KEY), -8);
			$auth_str = encrypt($str, AUTH_KEY);
			$auth = encrypt($username, AUTH_KEY).':'.$auth_str;

			// 记住登录
			if ($remember)
			{
				// 账号 密码
				wap_setcookie("WAP[auth]", $auth);
				wap_setcookie("WAP[auth$str]", encrypt($password, AUTH_KEY));
			}
			else
			{
				// 账号
				wap_setcookie("WAP[auth]", $auth, -1);
			}
		}

		// token
		wap_setcookie("WAP[auth_token]", encrypt($user['user_token'], AUTH_KEY), -1);


		MInterface::$login_id = $username;
		MInterface::$user_token = $user['user_token'];

		$userInfo = array('user_blacklist'=>$user['user_blacklist'], 'info'=>array());

		$mem->addCache('shop_user_info', $userInfo, 86400);

		return true;
	}
	else
	{
		return false;
	}
}

/**
 * 获得所有的友情链接
 *
 * @access  private
 * @return  array
 */
function get_friend_links()
{
	global $mInterface;

	$data = read_static_cache('friend_links', 0, 0, true);

	if ($data === false)
	{
		$sql = 'SELECT link_logo, link_name, link_url FROM ' . TABLEPRE."friend_link ORDER BY show_order";
		$res = $GLOBALS['db']->getAll($sql);

		write_static_cache('friend_links', $res, true);
	}
	else
	{
		$res = $data;
	}

	$links = array('img'=>array(), 'txt'=>array());


	foreach ($res AS $row)
	{
		if (!empty($row['link_logo']))
		{
			$links['img'][] = array(
            	'name' => $row['link_name'],
            	'url' => strpos($row['link_url'], '{$warehouse_url}') !== false ? str_replace('{$warehouse_url}', $warehouse_url, $row['link_url']) : $row['link_url'],
                'logo' => $row['link_logo'],
			);
		}
		else
		{
			$links['txt'][] = array(
            	'name' => $row['link_name'],
                'url' => strpos($row['link_url'], '{$warehouse_url}') !== false ? str_replace('{$warehouse_url}', $warehouse_url, $row['link_url']) : $row['link_url'],
			);
		}
	}

	return $links;
}

/**
 * 获得  当前环境的 URL 地址
 *
 * @access  public
 *
 * @return  void
 */
function get_url()
{
	$curr = strpos(PHP_SELF, ADMIN_PATH . '/') !== false ?
	preg_replace('/(.*)(' . ADMIN_PATH . ')(\/?)(.)*/i', '\1', dirname(PHP_SELF)) :
	dirname(PHP_SELF);

	$root = str_replace('\\', '/', $curr);

	if (substr($root, -1) != '/')
	{
		$root .= '/';
	}

	return get_domain() . $root;
}


/**
 * 取得当前的域名
 *
 * @access  public
 *
 * @return  string      当前的域名
 */
function get_domain()
{
	/* 协议 */
	$protocol = get_http();

	/* 域名或IP地址 */
	if (isset($_SERVER['HTTP_X_FORWARDED_HOST']))
	{
		$host = $_SERVER['HTTP_X_FORWARDED_HOST'];
	}
	elseif (isset($_SERVER['HTTP_HOST']))
	{
		$host = $_SERVER['HTTP_HOST'];
	}
	else
	{
		/* 端口 */
		if (isset($_SERVER['SERVER_PORT']))
		{
			$port = ':' . $_SERVER['SERVER_PORT'];

			if ((':80' == $port && 'http://' == $protocol) || (':443' == $port && 'https://' == $protocol))
			{
				$port = '';
			}
		}
		else
		{
			$port = '';
		}

		if (isset($_SERVER['SERVER_NAME']))
		{
			$host = $_SERVER['SERVER_NAME'] . $port;
		}
		elseif (isset($_SERVER['SERVER_ADDR']))
		{
			$host = $_SERVER['SERVER_ADDR'] . $port;
		}
	}

	return $protocol . $host;
}

/**
 * 获得 当前环境的 HTTP 协议方式
 *
 * @access  public
 *
 * @return  void
 */
function get_http()
{
	return (isset($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://';
}

/**
 * 引用模块文件
 *
 * @param	string	$path_file	要加载的子模块文件（不要后缀）
 */
function include_model_file($path_file){
	if (empty($path_file)){
		wap_header("Location: index.html");
	}

	if (is_file(MODEL_DIR . UI . '/' . $path_file . '.php')){
		return MODEL_DIR . UI . '/' . $path_file . '.php';
	}
	else {
		wap_header("Location: index.html");
	}
}

/**
 * 设置用户UI界面
 * 用户界面选择 (default为标准版, touch为触摸版)
 */
function get_ui_version()
{
	return 'touch';

	/*
	 $TouchUA = "/(Android|Ard|Phone|iOS|WebKit|wp)/i";
	 $SymbianUA = "/(Symbian)/i";
	 $PadUA = "/(Pad)/i";

	 $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);

	 $cookie_exists = false;

	 // 优先url参数
	 if (!empty($_REQUEST['v']))
	 {
		$v = trim($_REQUEST['v']);
		switch ($v)
		{
		case 1 : $v = 'default';break;
		case 2 : $v = 'touch';break;
		case 3 : $v = 'pad';break;
		}
		}
		// 读取历史cookie
		else if (!empty($_COOKIE['WAP']['revision']))
		{
		$v = $_COOKIE['WAP']['revision'];
		$cookie_exists = true;
		}
		// pad 识别
		else if (preg_match($PadUA, $useragent)
		|| (preg_match("/(Android)/i", $useragent) && !preg_match("/(Mobile)/i", $useragent))
		|| preg_match("/(Windows)/i", $useragent) || preg_match("/(Macintosh)/i", $useragent))
		{
		$v = 'pad';
		}
		// touch版识别
		else if (preg_match($TouchUA, $useragent))
		{
		$v = 'touch';
		}
		// default版识别
		else if (empty($useragent) || preg_match($SymbianUA, $useragent))
		{
		$v = 'default';
		}
		// 使用缺省设置
		else if (defined('DEFAULT_UI'))
		{
		$v = DEFAULT_UI;
		}

		if (!in_array($v, array('default', 'touch', 'pad')))
		{
		$v = 'touch';
		}

		// 记录用户 浏览版本COOKIE
		if (!$cookie_exists){
		wap_setcookie("WAP[revision]", $v);
		}

		return $v;
		*/
}

?>